import React, { useState, useEffect } from 'react';
import './ProductList.css';
import { DeleteOutlined, PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { Popconfirm, message, Tooltip } from 'antd';
import { productCartLimit } from './config';
import axios from 'axios';

const { maxQuantity, minQuantity } = productCartLimit;

const ProductList = () => {
  const [products, setProducts] = useState([]);

  // 通过useEffect, 监听全局input事件, 当输入的条形码长度为13时, 自动添加商品
  useEffect(() => {
    let barcode = '';
    let lastInputTime = 0;

    const handleGlobalInput = (e) => {
      console.log(e.key);
      // 忽略功能键和组合键
      // if (e.ctrlKey || e.altKey || e.metaKey || e.key.length > 1) 
      //   return;
      
      const now = Date.now();
      const timeSinceLastInput = now - lastInputTime;
      if (timeSinceLastInput > 1000) {
        // 如果两次输入时间间隔小于1秒, 则忽略此次输入
        barcode = '';
      }
      lastInputTime = now;

      if (e.key === 'Enter') {
        console.log('全局输入的条形码:', barcode);
        handleAddProduct(barcode);
        barcode = '';
      } else {
        barcode += e.key;
      }
    };

    console.log('添加全局输入事件监听')
    document.addEventListener('keydown', handleGlobalInput);
    return () => {
      document.removeEventListener('keydown', handleGlobalInput);
    }
  }, [products])

  const handleAddProduct = async (barcode) => {
    if (!barcode) {
      message.warning('请输入条形码');
      return;
    }

    // 检查是否已存在相同商品
    const existingProductIndex = products.findIndex(p => p.barcode === barcode);

    if (existingProductIndex >= 0) {
      // 如果已存在，增加数量
      const updatedProducts = [...products];
      const existingProduct = updatedProducts[existingProductIndex];
      if (existingProduct.quantity >= maxQuantity) {
        message.warning('商品数量已达到上限');
        return;
      }
      existingProduct.quantity += 1;
      setProducts(updatedProducts);
    } else {
      try {
        // 通过API查询商品
        const response = await axios.get(`/api/products/${barcode}`);
        if (response.data.code === 0) {
          setProducts([...products, {
            ...response.data.data,
            quantity: 1
          }]);
        } else {
          message.warning(`未找到对应的商品: ${barcode}`);
        }
      } catch (error) {
        message.error('查询商品失败');
      }
    }
  };

  const clearCart = () => {
    setProducts([]);
  };

  const handleDelete = (barcode) => {
    const newProducts = products.filter(product => product.barcode !== barcode);
    setProducts(newProducts);
    message.success('商品已删除');
  };

  const handleIncrease = (barcode) => {
    const product = products.find(product => product.barcode === barcode);
    if (!product) return;
    if (product.quantity >= maxQuantity) {
      message.warning('商品数量已达到上限');
      return;
    }
    product.quantity += 1;
    setProducts([...products]);
  };

  const handleDecrease = (barcode) => {
    setProducts(products.map(product =>
      product.barcode === barcode && product.quantity > 1
        ? { ...product, quantity: product.quantity - 1 }
        : product
    ));
  };

  const productCount = products.reduce((sum, product) => sum + product.quantity, 0);
  const totalPrice = products.reduce((sum, product) => sum + (product.price * product.quantity), 0);

  return {
    productCount,
    totalPrice,
    handleAddProduct,
    clearCart,
    render: (
      <div className="product-list">
        <div className="tit">购物车</div>
        <div className="product-list-container">
          {products.length === 0 ? (
            <div className="empty-cart">
              <img src="/images/cart-empty.jpeg" alt="购物车为空" className="empty-cart-image" />
              <p className="empty-cart-hint">快来扫码添加喜欢的商品吧</p>
            </div>
          ) : (
            <ul>
              {products.map((product) => (
                <li key={product.barcode}>
                  <Tooltip 
                    title={<img src={product.image} style={{ maxWidth: 400, maxHeight: 400 }} />}
                    overlayStyle={{ maxWidth: 'none' }}
                  >
                    <img src={product.image} alt={product.name} />
                  </Tooltip>
                  <div className="product-info">
                    <span className="product-name">{product.name}</span>
                    <span className="product-price">¥{product.price}元</span>
                    <div className="product-quantity">
                      <MinusOutlined
                        onClick={() => handleDecrease(product.barcode)}
                        className={`quantity-btn ${product.quantity <= minQuantity ? 'disabled' : ''}`}
                      />
                      <span className="quantity-value">{product.quantity}</span>
                      <PlusOutlined
                        onClick={() => handleIncrease(product.barcode)}
                        className={`quantity-btn ${product.quantity >= maxQuantity ? 'disabled' : ''}`}
                      />
                    </div>
                  </div>
                  <Popconfirm
                    title="确定要删除这个商品吗？"
                    onConfirm={() => handleDelete(product.barcode)}
                    okText="确定"
                    cancelText="取消"
                    placement="topRight"
                  >
                    <DeleteOutlined
                      className="delete-btn"
                    />
                  </Popconfirm>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    )
  };
};

export default ProductList;